<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { DataViewInstance, fmtDate, hBtns, hStatusTag, openDialog, request, statusSelect, TableColumnProps } from '../../../utils';
import { Plus, Sort } from '@element-plus/icons-vue';

const columns = [
  { label: '部门名称', prop: 'deptName', minWidth: 170 },
  { label: '排序', prop: 'deptSort' },
  {
    label: '状态',
    render: (_, { row }) => hStatusTag(row.status)
  },
  {
    label: '创建时间',
    minWidth: 170,
    render: (h, { row }) => h('span', fmtDate(row.createAt))
  },
  {
    label: '操作',
    width: 150,
    fixed: 'right',
    render: (_, { row }) => {
      return hBtns([
        { label: '修改', onClick: onEdit.bind(null, row, true) },
        { label: '新增', onClick: onEdit.bind(null, row, false) },
        { label: '删除', type: 'danger', onClick: onDelete.bind(null, row) }
      ])
    }
  }
] as TableColumnProps<any>[]

const tableRef = ref<DataViewInstance>()

const fetchAction = async (params: any) => {
  return request('/dept/list', { params })
}

const onEdit = (row?: any, isEdit = false) => {
  openDialog({
    vm: () => import('./edit.vue'),
    vmProps: { row, isEdit },
    dialogProps: {
      title: row ? '编辑' : '新增',
      onSubmitted: () => tableRef.value?.getData()
    }
  })
}

const onDelete = (row: any) => {
  tableRef.value?.deleteRows(
    () => request.post('/dept/delete', { id: row._id })
  )
}

const expandAll = ref(true)
const onToggleCollapse = () => {
  expandAll.value = !expandAll.value
}

onMounted(() => {
  tableRef.value?.getData()
})
</script>

<template>
  <UiDataView
    ref="tableRef"
    row-key="_id"
    :columns="columns"
    :fetch-action="fetchAction"
    :expand-all="expandAll"
    :config="{ pager: false }">
    <template #form="{ form, onSearch }">
      <ElFormItem label="部门名称">
        <ElInput placeholder="请输入部门名称" v-model="form.deptName" @keyup.enter="onSearch" />
      </ElFormItem>
      <ElFormItem label="状态">
        <ElSelect placeholder="请选择状态" clearable v-model="form.status" @change="onSearch">
          <ElOption v-for="_ in statusSelect" :key="_.value" v-bind="_" />
        </ElSelect>
      </ElFormItem>
    </template>
    <template #actions>
      <ElButton type="primary" plain :icon="Plus" @click="onEdit()">新增</ElButton>
      <ElButton type="info"plain :icon="Sort" @click="onToggleCollapse">折叠/展开</ElButton>
    </template>
  </UiDataView>
</template>
